import Vue from 'vue'
import VueRouter from 'vue-router'
import RouteRules from './modules/route-rules'
// progress bar
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Notification } from 'element-ui'
import { getPageTitle } from '@/locale'
import store from '@/store' // Vuex

// hack router push callback
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject);
  }
  return originalPush.call(this, location).catch(err => err);
}

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history', // 'hash'
  base: process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes: RouteRules
});

// NProgress Configuration
NProgress.configure({ showSpinner: false })

// no redirect whitelist
const whiteList = ['login']
const loginRoute = 'login'
const defaultRoutePath = '/dashboard'

//路由拦截器
router.beforeEach(async (to, from, next) => {
  NProgress.start(); // start progress bar

  // set page title
  document.title = getPageTitle(to.meta.title)

  //未登录
  if (!store.getters.token) {
    // 未登录,但在免登录白名单或该页面允许匿名访问,则直接进入
    if (whiteList.includes(to.name) || to.meta.AllowAnonymous) {
      return next()
    }
    // 跳转到登录页
    return next({ name: loginRoute, query: { redirect: to.fullPath } })
  }
  //已登录且要跳转的页面是登录页
  if (to.name === loginRoute) {
    return next({ path: defaultRoutePath }) // 跳转到主页
  }
  if (store.getters.asyncRoutes.length !== 0) {
    return next();
  }
  // generate dynamic router
  try {
    await store.dispatch('permission/generateRoutes');
    // 动态添加可访问路由表
    const asyncRoutes = store.getters.asyncRoutes;
    asyncRoutes.forEach(item => router.addRoute(item));
    // 请求带有 redirect 重定向时，登录自动重定向到该地址
    const redirect = decodeURIComponent(from.query.redirect || to.path)
    if (to.path === redirect) {
      // set the replace: true so the navigation will not leave a history record
      return next({ ...to, replace: true })
    }
    // 跳转到目的路由
    return next({ path: redirect })
  } catch (err) {
    Notification.error({ title: '错误', message: '请求用户权限失败，请重试' })
    store.dispatch('user/logout').finally((e) => {
      return next({ name: loginRoute, query: { redirect: to.fullPath } })
    });
  }
});

router.afterEach(() => {
  NProgress.done() // finish progress bar
  window.scrollTo(0, 0)
});


export default router